<template>
    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>

    <el-table :data="list" style="width: 100%">
        <el-table-column prop="specName" label="规格名称" />
        <el-table-column label="规格值" #default="scope">
        <div
            v-for="(item1, index1) in scope.row.specValue"
            :key="index1"
            style="padding: 5px; margin: 0;width: 100%;"
        >
            {{ item1.key }}：
            <span
            v-for="(item2, index2) in item1.valueList"
            :key="index2"
            class="div-atrr"
            >
            {{ item2 }}
            </span>
        </div>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" align="center" width="200"  #default="scope">
            <el-button type="primary" size="small" @click="editShow(scope.row)">
                修改
            </el-button>
            <el-button type="danger" size="small" @click="remove(scope.row.id)">
                删除
            </el-button>
        </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="pageParams.page"
        v-model:page-size="pageParams.limit"
        :page-sizes="[2,10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />


    <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
        <el-form label-width="120px">
            <el-form-item label="规格名称" >
                <el-input v-model="productSpec.specName"/>
            </el-form-item>
            <el-form-item>
                <el-button size="default" type="success" @click="addSpec">
                    添加新规格
                </el-button>
            </el-form-item>
            <el-form-item label="" v-for="(item , index) in productSpec.specValue" :key="index">
                <el-row>
                    <el-col :span="10">
                        <el-input
                                v-model="item.key"
                                placeholder="规格"
                                style="width: 90%;"
                                />
                    </el-col>
                    <el-col :span="10">
                        <el-input
                                v-model="item.valueList"
                                placeholder="规格值(如:白色,红色)"
                                style="width: 90%;"
                                />
                    </el-col>
                    <el-col :span="4">
                        <el-button size="default" type="danger" @click="delSpec(index)">删除</el-button>
                    </el-col>
                </el-row>  
            </el-form-item>
            <el-form-item align="right">
                <el-button type="primary" @click="saveOrUpdate">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>


</template>

<script setup>
import { ref , onMounted } from 'vue'
import { FindProductSpecPageList,SaveProductSpec,UpdateProductSpecById,DeleteProductSpecById } from '@/api/productSpec';
import { ElMessage,ElMessageBox } from 'element-plus';

// 表格数据模型
const list = ref([
    // {
    //     "id": 2,
    //     "createTime": "2023-05-06 12:56:08",
    //     "specName": "笔记本电脑",
    //     "specValue": [{"key":"内存","valueList":["8G","18G","32G"]}]
    // },
])

// 分页条数据模型
const total = ref(0)

const pageParamsForm = {
    page: 1,
    limit: 2
}

const pageParams = ref(pageParamsForm)

const dialogVisible = ref(false)

const productSpecForm = {
    id: '',
    specName: '',
    specValue: []
}

const productSpec = ref(productSpecForm)


//==========================================================================

onMounted(()=>{
    fetchData()
})

const fetchData = async () => {

    const { data } = await FindProductSpecPageList(pageParams.value.page,pageParams.value.limit)
    data.list.forEach(item => {
        item.specValue = JSON.parse(item.specValue)
    })
    list.value = data.list
    total.value = data.total
}

const handleSizeChange = (size) => {
    pageParams.value.limit = size
    fetchData()
}

const handleCurrentChange = (number) => {
    pageParams.value.page = number
    fetchData()
}

const addShow = () => {
    dialogVisible.value = true
    productSpec.value = {
        id: '',
        specName: '',
        specValue: []
    }
}


const saveOrUpdate = () => {
    if(!productSpec.value.id){
        saveData()
    }else{
        upateData()
    }
}

const saveData = async () => {
    //克隆一个新的对象
    const productSpecClone = JSON.parse(JSON.stringify(productSpec.value))
    productSpecClone.specValue.forEach(item => {
        item.valueList = item.valueList.split(',') //把字符串变成数组   '白色,黑色'  =>  ['白色','黑色']
    })
    productSpecClone.specValue = JSON.stringify(productSpecClone.specValue) //把规格变成字符串  {'key':'颜色','valueList':['白色','黑色']}

    await SaveProductSpec(productSpecClone)
    ElMessage.success('操作成功')
    dialogVisible.value = false
    fetchData()
}

const upateData = async () => {
    const productSpecClone = JSON.parse(JSON.stringify(productSpec.value))
    productSpecClone.specValue.forEach(item=>{
        if(typeof item.valueList === 'string'){
            item.valueList = item.valueList.split(',')
        }        
    })
    productSpecClone.specValue = JSON.stringify(productSpecClone.specValue)
    await UpdateProductSpecById(productSpecClone)
    ElMessage.success('操作成功')
    dialogVisible.value = false
    fetchData()
}

//页面添加规格操作
const addSpec = () => {
    productSpec.value.specValue.push({})
}

//页面删除规格元素
const delSpec = (index) => {
    //splice()函数 对数组 添加/删除 元素，然后，返回被删除的项目
    //index 必须。整数,规定添加/删除的项目的位置，使用负数可以从数组的结尾处规定位置
    //howmany 必须。要删除的元素数量。如果设置为0,则不会删除项目
    //item1,...itemx  可选。向数组添加的新元素
    productSpec.value.specValue.splice(index, 1)
}

const editShow = (row) => {
    productSpec.value = row
    dialogVisible.value = true
}

//删除
const remove = async id => {
    debugger
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await DeleteProductSpecById(id)
      ElMessage.success('删除成功')
      fetchData()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}
</script>

<style scoped>
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
    
.div-atrr {
  padding: 5px 10px;
  margin: 0 10px;
  background-color: powderblue;
  border-radius: 10px;
}

</style>